package com.zn.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zn.Vo.AdminAndCodeVo;
import com.zn.bean.Admin;
import com.zn.mapper.AdminMapper;
import com.zn.service.AdminService;
import com.zn.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 码农小周
 * @since 2023-05-12
 */
@Service
@Slf4j
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    @Override
    public Result<Long> login(AdminAndCodeVo adminAndCodeVo, HttpServletRequest request) {

        String sessionCode = (String) request.getSession().getAttribute("code");

//        判断是否为空，验证码，用户名，密码
        if (StringUtils.isEmpty(adminAndCodeVo.getLoginName()) || StringUtils.isEmpty(adminAndCodeVo.getPassWord()) || StringUtils.isEmpty(adminAndCodeVo.getCode())) {
            return Result.error(501, "参数不能为空");
        }

//        对密码进行加密
        String md5PassWord = DigestUtils.md5DigestAsHex(adminAndCodeVo.getPassWord().getBytes());

//        判断是否相等
        if (!sessionCode.equals(adminAndCodeVo.getCode())) {
            return Result.error(501, "验证码错误");
        }


//        创建条件构造器
        LambdaQueryWrapper<Admin> adminLambdaQueryWrapper = new LambdaQueryWrapper<>();
        adminLambdaQueryWrapper.eq(Admin::getLoginName, adminAndCodeVo.getLoginName());

//        通过用户名获取用户信息
        Admin dbAdmin = this.getOne(adminLambdaQueryWrapper);

//        判断用户是否存在
        if (null == dbAdmin) {
            return Result.error(501, "用户不存在");
        }

//        判断密码是否正确
        if (!md5PassWord.equals(dbAdmin.getPassWord())) {
            return Result.error(501, "密码错误");
        }

//        判断用户是否被禁用
        if (dbAdmin.getStatus() == 0) {
            return Result.error(501, "该用户已被禁用");
        }

        return Result.success(dbAdmin.getAdminId());
    }

    @Override
    public Result<Admin> byAdminId(Long adminId) {
        Admin dbAdmin = this.getById(adminId);
        if (null == dbAdmin) {
            return Result.error(501, "当前用户不存在");
        }
        return Result.success(dbAdmin);

    }


    @Override
    public Result<Page<Admin>> pagSelect(Long page, Long pageSize, String adminName) {
        //创建分页对象
        Page<Admin> pageInfo = new Page<>(page, pageSize);

        //创建条件构建器
        LambdaQueryWrapper<Admin> adminLambdaQueryWrapper = new LambdaQueryWrapper<>();

        //如果adminName有值，则加上此过滤条件
        adminLambdaQueryWrapper.like(StringUtils.isNotEmpty(adminName), Admin::getAdminName, adminName);
        //排序条件
//        第一个参数：表示是否将该条件添加到SQL中
//        第二个参数：表示是否升序排列
//        第三个参数：表示是排序参数
//        SELECT * FROM admin ORDER BY authority DESC, `status` ASC,update_time DESC;
        adminLambdaQueryWrapper.orderBy(true, false, Admin::getAuthority)
                .orderBy(true, true, Admin::getStatus)
                .orderBy(true, false, Admin::getUpdateTime);

        //查询
        pageInfo = this.page(pageInfo, adminLambdaQueryWrapper);
        return Result.success(pageInfo);
    }

    @Override
    public Result<String> del(Long adminId) {
        if (null == adminId) {
            return Result.error(501, "请选择要删除的数据");
        }
        Admin dbAdmin = this.getById(adminId);

        if (null == dbAdmin){

            return Result.error(501,"该用户不存在");
        }

        if (1 == dbAdmin.getStatus()) {
            return Result.error(501, "请先禁用管理员账号再删除");
        }
        boolean b = this.removeById(adminId);
        return b ? Result.success("删除成功") : Result.error(501, "删除失败");
    }

    @Override
    public Result<String> addAdmin(Admin admin) {

//        判断必填参数是否为空
        if (StringUtils.isEmpty(admin.getAdminName()) || StringUtils.isEmpty(admin.getLoginName()) || StringUtils.isEmpty(admin.getPhone())) {
            return Result.error(501, "参数不能为空");
        }

//        判断该用户权限是否为超级管理员
        if (0 == admin.getAuthority()) {
            return Result.error(501, "该用户权限不足");
        }

        admin.setAuthority(0);

//        条件构造器
        LambdaQueryWrapper<Admin> adminLambdaQueryWrapper = new LambdaQueryWrapper<>();
        adminLambdaQueryWrapper.eq(Admin::getLoginName, admin.getLoginName()).or().eq(Admin::getPhone, admin.getPhone());

//        db数据的条数
        Long total = this.count(adminLambdaQueryWrapper);

//        设置初始密码
        admin.setPassWord(DigestUtils.md5DigestAsHex("123456".getBytes()));

//        判断该用户信息是否存在
        if (total > 0) {
            return Result.error(501, "用户名或手机号已存在");
        }
        this.save(admin);
        return Result.success("操作成功");
    }

    @Override
    public Result<String> editAdmin(Admin admin) {
//        判断必填参数是否为空
        if (StringUtils.isEmpty(admin.getAdminName()) || StringUtils.isEmpty(admin.getLoginName()) || StringUtils.isEmpty(admin.getPhone())) {
            return Result.error(501, "参数不能为空");
        }
//        adminId必须存在
        if (null == admin.getAdminId()) {
            throw new RuntimeException();
        }

//        数据库数据
        Admin dbAdmin = this.getById(admin.getAdminId());

        if (null == dbAdmin) {
            return Result.error(501, "当前用户不存在");
        }

        if (admin.getPassWord() != null) {
            String md5PassWord = DigestUtils.md5DigestAsHex(admin.getPassWord().getBytes());
            //        判断密码是否和之前一致
            if (md5PassWord.equals(dbAdmin.getPassWord())) {
                log.info("我是修改密码");
                return Result.error(501, "修改密码和之前密码一致");
            }
            admin.setPassWord(md5PassWord);
        }


//        判断当前修改数据是否和数据库数据一样

        if (admin.getLoginName().equals(dbAdmin.getLoginName())) {
            admin.setLoginName(null);
        }
        if (admin.getPhone().equals(dbAdmin.getPhone())) {
            admin.setPhone(null);
        }


//        当修改数据和当前数据库数据不一致，则查询”登录名“或者”手机号“是否和其他数据存在一致
//        根据修改的数据的用户名和手机号，查询是否存在一样的用户名和手机号，true则不能修改，提示存在手机号和用户名
        LambdaQueryWrapper<Admin> adminLambdaQueryWrapper = new LambdaQueryWrapper<>();
        adminLambdaQueryWrapper.eq(Admin::getLoginName, admin.getLoginName());
        long loginTotal = this.count(adminLambdaQueryWrapper);
//        判断该用户信息是否存在
        if (loginTotal > 0) {
            return Result.error(501, "用户名已存在");
        }

//        判断手机号是否已存在
        LambdaQueryWrapper<Admin> adminPhoneLambdaQueryWrapper = new LambdaQueryWrapper<>();
        adminPhoneLambdaQueryWrapper.eq(Admin::getPhone, admin.getPhone());
        long phoneTotal = this.count(adminLambdaQueryWrapper);
        if (phoneTotal > 0) {
            return Result.error(501, "手机号已存在");
        }

        this.updateById(admin);
        return Result.success("修改成功");
    }

    @Override
    public Result<String> editAdminStatus(Admin admin) {


        if (0 == admin.getAuthority()) {
            return Result.error(501, "该用户权限不足");
        }
        admin.setAuthority(0);
        boolean b = this.updateById(admin);
        return b ? Result.success("修改状态成功") : Result.error(501, "修改状态失败");
    }

    @Override
    public Result<String> resetting(Admin admin) {

        //  adminId必须存在
        if (null == admin.getAdminId()) {
            throw new RuntimeException();
        }

//        数据库数据
        Admin dbAdmin = this.getById(admin.getAdminId());

        if (1 == dbAdmin.getStatus()) {
            return Result.error(501, "该用户未禁用，请先禁用");
        }

//        设置初始密码
        admin.setPassWord(DigestUtils.md5DigestAsHex("123456".getBytes()));

        boolean b = this.updateById(admin);

        return b ? Result.success("重置密码成功") : Result.error(501,"重置密码失败");
    }
}
